const mouthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

const money = document.querySelector("#money");
const why = document.querySelector(".why");
const instructions = document.querySelector(".instructions");
const cycle = document.querySelector("#cycle-select");
const day = document.querySelector("#day-select");
const interest = document.querySelector("#interest");
const warn = document.querySelector(".warn");

const btn = document.querySelector(".btn");
const resest = document.querySelector(".resest");

const huey = document.querySelector("#huey");
const dewey = document.querySelector("#dewey");

const everyMonth = document.querySelector(".everyMonth");
const allInterest = document.querySelector(".allInterest");
const allMoney = document.querySelector(".allMoney");

const record = document.querySelector(".record");
const recordData = document.querySelector(".recordData");
const clean = document.querySelector(".clean");

const myAudio = document.querySelector("#myAudio");
const fengAudio = document.querySelector("#fengAudio");
const fuckAudio = document.querySelector("#fuckAudio");

const borrowDate = document.querySelector("#borrowDate");
const payDate = document.querySelector("#payDate");

// const copy = document.querySelector(".copy");

const recordArr = [];

// copy.addEventListener("click", () => {
//   if (everyMonth.innerHTML === "*" || everyMonth.innerHTML === "") return;
//   navigator.clipboard.writeText(everyMonth.innerText);
//   warn.innerHTML = "**复制成功**";
//   setTimeout(() => {
//     if (warn.innerHTML === "**复制成功**") {
//       warn.innerHTML = "";
//     }
//   }, 2000);
// });

why.addEventListener("click", () => {
  instructions.style.display = "block";
  instructions.children[0].style.display = "block";
  fengAudio.play();
});
instructions.addEventListener("click", () => {
  instructions.style.display = "none";
  fengAudio.pause();
});
cycle.addEventListener("change", () => {
  if (cycle.value === "12") day.value = "0";
  affectDate();
});

borrowDate.addEventListener("change", () => {
  payDate.min = borrowDate.value;
  payDateMax();
});

payDate.addEventListener("change", () => {
  dateChangeCycle();
  borrowDateMax();
});

window.addEventListener("load", () => {
  payDate.min = borrowDate.value = new Date()
    .toLocaleDateString()
    .replace(/\//g, "-");

  payDateMax();
  initSelect();
});

btn.addEventListener("click", () => {
  if (!checkInput()) return;
  myAudio.play();
  affectDate();
  count();
});

resest.addEventListener("click", () => {
  location.reload();
});

let time = null;
record.addEventListener("click", () => {
  if (allMoney.innerHTML === "*") {
    return;
  }
  if (time) {
    clearTimeout(time);
  }
  time = setTimeout(() => {
    recordArr.push(allMoney.innerHTML);
    recordData.innerHTML = recordArr.reduce((pre, cur, i) => {
      return (
        pre +
        `
          <div>
            ${i + 1}：${cur}
          </div>
          `
      );
    }, "");
    time = null;
  }, 500);
});

clean.addEventListener("click", () => {
  fuckAudio.play();
  recordArr.length = 0;
  recordData.innerHTML = "";
});

// 先息后本 总利息
function moneyMore(base, cycle, interest) {
  base = Number(base);
  cycle = Number(cycle);
  interest = Number(interest);

  const everyDate = getDate();
  let allInterest1 = 0;
  everyMonth.innerHTML = "";
  let temp = "";
  day.value !== "0" && (cycle += 1);
  for (let i = 0; i < cycle; i++) {
    let thisMonthInterest;
    thisMonthInterest =
      everyDate[i].thisMonthDays *
      everyDayInterest(base, everyDate[i].thisYear);

    thisMonthInterest = to_two(thisMonthInterest);
    allInterest1 += thisMonthInterest;

    temp += `
    <div>
      第${addZero(i + 1)}期（${everyDate[i].ymd}）：本金 ${
      i === cycle - 1 ? base : 0
    } + 本月利息 ${thisMonthInterest} = ${
      thisMonthInterest + (i === cycle - 1 ? base : 0)
    }
    </div>
    `;
  }
  everyMonth.innerHTML = temp;
  allInterest.innerHTML = to_two(allInterest1);
  allMoney.innerHTML = `${money.value} + ${to_two(allInterest1)} = ${
    Number(money.value) + to_two(allInterest1)
  }`;
}

// 每月等额 总利息
function moneyLess(base, cycle, interest) {
  base = Number(base);
  cycle = Number(cycle);
  interest = Number(interest);

  day.value !== "0" && (cycle += 1);

  let allInterest1 = 0;
  let monthPay = new Map();
  const everyDate = getDate();
  for (let i = 0; i < cycle; i++) {
    const thisMonthInterest =
      everyDate[i].thisMonthDays *
      everyDayInterest(base * ((cycle - i) / cycle), everyDate[i].thisYear);

    monthPay.set(i, thisMonthInterest);
    allInterest1 += thisMonthInterest;
  }
  allInterest.innerHTML = to_two(allInterest1);
  everyMonth.innerHTML = "";
  let temp = "";
  monthPay.forEach((value, key) => {
    temp += `
    <div>
      第${addZero(key + 1)}期（${everyDate[key].ymd}）：本金 ${to_two(
      base / cycle
    )} + 本月利息 ${to_two(value)} = ${to_two(base / cycle + value)}
    </div>
    `;
  });
  everyMonth.innerHTML = temp;

  allMoney.innerHTML = `${money.value} + ${to_two(allInterest1)} = ${to_two(
    Number(money.value) + Number(allInterest1)
  )}`;
}

// 计算利息和每月还多少
function count() {
  if (huey.checked) {
    moneyMore(money.value, cycle.value, interest.value);
  }

  if (dewey.checked) {
    moneyLess(money.value, cycle.value, interest.value);
  }
}

function checkInput() {
  if (!money.value || !interest.value || !borrowDate.value) {
    !money.value && (warn.innerHTML = "**请输入借款金额!**");
    !interest.value && (warn.innerHTML = "**请输入年利息!**");
    !borrowDate.value && (warn.innerHTML = "**请输入日期!**");
    return false;
  } else {
    warn.innerHTML = "";
    return true;
  }
}

function to_two(v) {
  return Math.ceil(v * 100) / 100;
}

function getDate() {
  const res = [],
    ymd = borrowDate.value.split("-");

  let y = Number(ymd[0]),
    m = Number(ymd[1]), // 0-11 12个月
    d = Number(ymd[2]),
    v = Number(cycle.value);

  day.value !== "0" && (v += 1);

  const firstDay = d; // 第一次是几号
  let leapYear = isLeapYear(y),
    thisMonthDays;

  for (let i = 0; i < v; i++) {
    if (m / 11 > 1) {
      ++y;
      leapYear = isLeapYear(y);
      m = 0;
    }

    const thirty = [4, 6, 9, 11];

    // 非闰年
    if (!leapYear && firstDay > 28) {
      if (m + 1 === 2) {
        d = 28;
      } else if (firstDay > 30 && thirty.includes(m + 1)) {
        d = 30;
      } else {
        d = firstDay;
      }
    } else if (leapYear && firstDay > 29) {
      // 闰年
      if (m + 1 === 2) {
        d = 29;
      } else if (firstDay > 30 && thirty.includes(m + 1)) {
        d = 30;
      } else {
        d = firstDay;
      }
    }

    if (day.value !== "0" && i === v - 1) {
      thisMonthDays = Number(day.value) + 1;
    } else {
      thisMonthDays = mouthDays[m];
      i === v - 1 && thisMonthDays++;
    }

    res.push({
      ymd: `${y}-${addZero(m + 1)}-${addZero(d)}`,
      thisMonthDays,
      thisYear: y,
    });
    ++m;
  }
  return res;
}

function addZero(d) {
  return d < 10 ? "0" + d : d;
}
// 判断是不是闰年
function isLeapYear(y) {
  y = Number(y);
  if (!(y % 100) && !(y % 400)) {
    return true;
  } else if (y % 100 && !(y % 4)) {
    return true;
  }
  return false;
}

function initSelect() {
  let temp = "";
  for (let i = 0; i < 13; i++) {
    temp += `<option value="${i}">${i}个月</option>`;
  }
  cycle.innerHTML = temp;

  temp = "";
  for (let i = 0; i < 32; i++) {
    temp += `<option value="${i}">${i}天</option>`;
  }
  day.innerHTML = temp;
}

function howManyMouthAndDays() {
  if (!borrowDate.value || !payDate.value) return;

  const bymd = borrowDate.value.split("-").map((item) => Number(item));
  const pymd = payDate.value.split("-").map((item) => Number(item)); // 2000 02 28

  pymd[0] > bymd[0] && (pymd[1] += 12);

  let m = pymd[1] - bymd[1],
    d = 0;

  if (m === 0) {
    // 不满一个月
    m = 0;
    d = pymd[2] - bymd[2];
  } else if (m === 1 && pymd[2] < bymd[2]) {
    // 不满一个月
    m = 0;
    d = mouthDays[bymd[1] - 1] - bymd[2] + 1 + pymd[2];
  } else {
    // 满一个月
    if (pymd[2] >= bymd[2]) {
      d = pymd[2] - bymd[2];
    } else {
      // 还款日比借款日小
      let tempM = pymd[1] > 12 ? (pymd[1] -= 12) : pymd[1];
      tempM = tempM === 1 ? 12 : tempM;
      d = mouthDays[tempM - 1] - bymd[2] + pymd[2];
      m -= 1;
    }
  }

  return {
    m,
    d,
  };
}

function dateChangeCycle() {
  const { m, d } = howManyMouthAndDays() || { m: 0, d: 0 };
  cycle.value = m;
  day.value = d;
}

function cycleChangeDate() {
  if (!borrowDate.value) return;
  const m = Number(cycle.value),
    d = Number(day.value);
  const bymd = borrowDate.value.split("-").map((item) => Number(item));
  const by = bymd[0],
    bm = bymd[1],
    bd = bymd[2];

  let yy, mm, dd;

  yy = by;
  mm = m + bm;
  if (mm > 12) {
    yy += 1;
    mm -= 12;
  }

  dd = d + bd;

  if (dd > mouthDays[mm - 1]) {
    mm += 1;
    if (mm > 12) {
      mm -= 12;
      yy += 1;
    }
    dd = dd - mouthDays[mm - 1];
  }

  mm = mm < 10 ? "0" + mm : mm;
  dd = dd < 10 ? "0" + dd : dd;

  return {
    y: yy,
    m: mm,
    d: dd,
  };
}

function borrowDateMax() {
  borrowDate.max = payDate.value || "";
}

function payDateMax() {
  payDate.max = payDate.min
    .split("-")
    .map((item, i) => {
      if (i === 0) {
        return String(Number(item) + 1);
      } else {
        return item;
      }
    })
    .join("-");
}

// 日利息
function everyDayInterest(base, year) {
  const YearInterest = Number(interest.value) / 100;

  if (isLeapYear(year)) {
    return (base * YearInterest) / 366;
  } else {
    return (base * YearInterest) / 365;
  }
}

function affectDate() {
  const { y, m, d } = cycleChangeDate();
  payDate.value = `${y}-${m}-${d}`;
}
// let temp =
//   Math.abs(
//     (payDate.valueAsNumber - borrowDate.valueAsNumber) / 1000 / 3600 / 24
//   ) + 1;
